package com.xxl.job.core.commons.annotation.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xxl.job.core.commons.annotation.CheckListRepeat;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.List;

/**
 * @author : xingsongtan@qq.com
 * @date : 15:27 2019/9/23
 */
@Slf4j
public class CheckListRepeatImpl implements ConstraintValidator<CheckListRepeat, Object> {
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        // 如果为空，则不做校验
        if (null == value) {
            return true;
        }
        List<Object> list;
        try {
            list = JSONArray.parseArray(JSON.toJSONString(value), Object.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("校验类型异常，CheckListRepeat 方法只能校验list！");
            return false;
        }
        // 进行校验
        HashSet<Object> hashSet = new HashSet<>(list);
        if (list.size() != hashSet.size()) {
            return false;
        }
        return true;
    }

    @Override
    public void initialize(CheckListRepeat constraintAnnotation) {

    }
}
